<?php

defined('BASEPATH') or die('forbidden');

/**
 * 后台判断权限
 * @param int $rank
 * @param string $catalog
 * @param string $action
 * @param string $segment
 */
function check_level($rank = 50, $catalog = null, $action = null, $segment = null) {
    $framework = &get_instance('controller');
    $action = $action == 'flexigrid' ? 'index' : $action;
    $segment = $segment == 'flexigrid' ? 'index' : $segment;
    $type = $framework->input->post("type");
    //AJAX操作时提示的权限
    $action = $action == 'multi' && $type == 'delete' ? 'delete' : ($action == 'multi' ? 'edit' : $action);
    $segment = $segment == 'multi' && $type == 'delete' ? 'delete' : ($segment == 'multi' ? 'edit' : $segment);
    if (!$framework->auth->is_login()) {
        if (is_ajax()) {
            json_output(0, $framework->auth->error);
        } else {
            error($framework->auth->error, site_url('index/login/') . '?url=' . current_url(1), 1000);
        }
    }
    if (!$framework->auth->check_level($rank, $catalog, $action, $segment)) {
        if (segment(0) == 'index' || segment(0) == '') {
            $framework->auth->logout(base_url());
            go(site_url('index/login'));
        } else {
            if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
                json_output(0, translate('C_INSUFFICIENT_PERMISSIONS'));
            } else {
                show_error(translate('C_INSUFFICIENT_PERMISSIONS'), 403, translate('ERROR') . translate('C_INSUFFICIENT_PERMISSIONS') . "...");
            }
        }
    }
}

/**
 * 判断会员是否登录
 * @return boolean 
 */
function check_login() {
    $framework = &get_instance('controller');
    return !$framework->auth->is_login() ? false : true;
}

/**
 * 后台菜单权限判断
 * @param int $rank 权限等级
 * @param string $catalog 目录
 * @param string $action 动作
 * @return mixed
 */
function check_level_menu($rank = 1, $catalog = null, $action = null, $segment = null) {
    $framework = &get_instance('controller');
    return $framework->auth->check_level($rank, $catalog, $action, $segment);
}

function get_user_search($name) {
    return "<a href=\"javascript:;\" class=\"searchit\" name=\"{$name}\" title=\"" . translate('DETAIL') . "\"><img src=\"images/search.png\" /></a>";
}

function get_role_data($role_id) {
    $framework = &get_instance('controller');
    $list = $framework->db->simple("SELECT * FROM {pre}role");
    $one = array();
    foreach ($list as $m => $n) {
        if ($n['id'] == $role_id) {
            $one = $n;
            break;
        }
    }
    if ($one) {
        if ($one['rank'] == 100) {
            $result = array();
            foreach ($list as $m => $n) {
                $result[$n['id']] = $n;
            }
            return $result;
        } else {
            return get_role_childen_data($list, $one['id']);
        }
    } else {
        return array();
    }
}

function get_role_childen_data($list, $father_id = 0) {
    $result = array();
    foreach ($list as $m => $n) {
        if ((string) $n['father_id'] === (string) $father_id) {
            $result[$n['id']] = $n;
            $result = $result + get_role_childen_data($list, $n['id']);
        }
    }
    return $result;
}

function get_role_childen_ids($role_id) {
    $list = get_role_data($role_id);
    $ids = array();
    foreach ($list as $m => $n) {
        $ids[] = $n['id'];
    }
    return $ids;
}

/**
 * 提示信息
 * @param string $result  结果 success,error
 * @param int $id 刷新的行ID,将会将该行高亮闪烁
 * @param string $refresh_id 刷新的列表ID
 */
function cp_tips($result, $id = 0, $refresh_id = "#flexigrid") {
    $dialogclose = $result == 'success' ? "window.parent.$('#edit').hide();
    window.parent.$('#add').hide();
    window.parent.$('#dialogit').hide();" : '';
    $text = $result == 'success' ? translate('C_TIPS_SUCCESS_TEXT') : translate('C_TIPS_ERROR_TEXT');
    //指定元素背景渐变
    $callback = $id ? ",window.parent.row_flash('{$id}')" : '';
    echo "<script type='text/javascript'>
    window.parent.SG.admin.{$result}('{$text}',0,'{$refresh_id}' {$callback});
    {$dialogclose}
    </script>";
    exit;
}

function get_method_url($class, $method) {
    $url = trim($_SERVER['PATH_INFO'], '/');
    if ($method && strripos($url, $method) === false)
        $url .= "/{$method}";
    $class = strtolower(str_replace(array('_Controller', '_Model'), '', $class));
    $s = $class . '/' . $method;
    return substr($url, 0, strripos($url, $s) + strlen($s));
}

function get_used_status() {
    $cpu_usage = $mem_usage = $hd_avail = $hd_used = $hd_usage = $task_running = $hd_total = 0;
    $fp = popen('top -b -n 1 | grep -E "^(Cpu|Mem|Tasks)"', "r"); //获取某一时刻系统cpu和内存使用情况
    $rs = "";
    while (!feof($fp)) {
        $rs .= fread($fp, 1024);
    }
    pclose($fp);
    if ($rs) {
        $sys_info = explode("\n", $rs);
        $task_info = explode(",", $sys_info[0]); //进程 数组
        $cpu_info = explode(",", $sys_info[1]);  //CPU占有量  数组
        $mem_info = explode(",", $sys_info[2]); //内存占有量 数组
        //正在运行的进程数
        $task_running = trim(trim($task_info[1], 'running'));
        //CPU占有量
        $cpu_usage = trim(trim($cpu_info[0], 'Cpu(s): '), '%us');  //百分比
        //内存占有量
        $mem_total = trim(trim($mem_info[0], 'Mem: '), 'k total');
        $mem_used = trim($mem_info[1], 'k used');
        $mem_usage = round(100 * intval($mem_used) / intval($mem_total), 2);  //百分比
        /* 硬盘使用率 begin */
        $fp = popen('df -lh | grep -E "^(/)"', "r");
        $rs = fread($fp, 1024);
        pclose($fp);
        $rs = preg_replace("/\s{2,}/", ' ', $rs);  //把多个空格换成空
        $hd = explode(" ", $rs);
        $hd_total = trim($hd[1], 'G'); //硬盘总空间
        $hd_used = trim($hd[2], 'G'); //硬盘已用空间
        $hd_avail = trim($hd[3], 'G'); //磁盘可用空间大小
        $hd_usage = trim($hd[4], '%'); //硬盘占用百分比
        /* 硬盘使用率 end */
    }
    $result = array('cpu_usage' => $cpu_usage, 'mem_usage' => $mem_usage, 'hd_used' => $hd_used, 'hd_usage' => $hd_usage, 'hd_total' => $hd_total, 'hd_usage' => $hd_usage, 'task_running' => $task_running);
    return $result;
}

/**
 * 写入后台操作日志
 * @param string $title 操作简介
 * @param mixed $before 旧数据
 * @param mixed $after 新数据
 */
function insert_log($title = array(), $before = null, $after = null) {
    if ($before && $after) {
        get_int_type($before);
        get_int_type($after);
        if (is_array($before) && is_array($after)) {
            $original = array_intersect($before, array_diff($before, $after));
            $changed = array_intersect($after, array_diff($after, $before));
        } else {
            $original = $before;
            $changed = $after;
        }
        $content = $original || $changed ? addslashes(json_encode(array('before' => $original, 'after' => $changed))) : '';
    } else {
        $content = '';
    }
    if (!$title)
        return;
    $framework = &get_instance('controller');
    $values = array('name' => $framework->auth->username, 'url' => current_url(), 'title' => addslashes($title), 'content' => $content, 'createtime' => time());
    $framework->db->insert("{pre}admin_log", $values);
}

function check_env() {
    //预定义查询变量
    $info = array(
        'safe_mode' => array(translate('GENERAL_CHECKENV_INFO_SAFE_MODE'), 0),
        'allow_url_fopen' => array(translate('GENERAL_CHECKENV_INFO_ALLOW_URL_FOPEN'), 'OFF', translate('GENERAL_CHECKENV_SUGGEST_CLOSE')),
        'register_globals' => array(translate('GENERAL_CHECKENV_INFO_REGISTER_GLOBALS'), 'OFF', translate('GENERAL_CHECKENV_SUGGEST_CLOSE')),
        'magic_quotes_gpc' => array(translate('GENERAL_CHECKENV_INFO_MAGIC_QUOTES_GPC'), 'ON', translate('GENERAL_CHECKENV_SUGGEST_OPEN')),
        'short_open_tag' => array(translate('GENERAL_CHECKENV_INFO_SHORT_OPEN_TAG'), 'ON', translate('REQUIRE')),
        'magic_quotes_runtime' => array(translate('GENERAL_CHECKENV_INFO_MAGIC_QUOTES_RUNTIME'), 'OFF', translate('GENERAL_CHECKENV_SUGGEST_CLOSE')),
        'enable_dl' => array(translate('GENERAL_CHECKENV_INFO_ENABLE_DL'), 'OFF', translate('GENERAL_CHECKENV_SUGGEST_OPEN')),
        'display_errors' => array(translate('GENERAL_CHECKENV_INFO_DISPLAY_ERRORS'), 0),
        'post_max_size' => array(translate('GENERAL_CHECKENV_INFO_POST_MAX_SIZE'), 0),
        'upload_max_filesize' => array(translate('GENERAL_CHECKENV_INFO_UPLOAD_MAX_FILESIZE'), 0),
        'memory_limit' => array(translate('GENERAL_CHECKENV_INFO_MEMORY_LIMIT'), 1),
    );

    $fun = array(
        'apc_cache_info' => array(translate('GENERAL_CHECKENV_FUNC_APC_CACHE_INFO'), 0, translate('GENERAL_CHECKENV_SUGGEST_OPEN')),
        'curl_init' => array(translate('GENERAL_CHECKENV_FUNC_CURL_INIT'), 0),
        'mysql_close' => array(translate('GENERAL_CHECKENV_FUNC_MYSQL_CLOSE'), 'ON', translate('REQUIRE')),
        'gd_info' => array(translate('GENERAL_CHECKENV_FUNC_GD_INFO'), 'ON', translate('REQUIRE')),
        'socket_accept' => array(translate('GENERAL_CHECKENV_FUNC_SOCKET_ACCEPT'), 0),
        'xml_set_object' => array(translate('GENERAL_CHECKENV_FUNC_XML_SET_OBJECT'), 'ON', translate('GENERAL_CHECKENV_SUGGEST_OPEN')),
        'gzclose' => array(translate('GENERAL_CHECKENV_FUNC_GZCLOSE'), 0),
        'mcrypt_cbc' => array(translate('GENERAL_CHECKENV_FUNC_MCRYPT_CBC'), 0),
        'preg_match' => array(translate('GENERAL_CHECKENV_FUNC_PREG_MATCH'), 'ON', translate('REQUIRE')),
    );

    $dir = array(
        '/api/application/logs/' => array(translate('GENERAL_CHECKENV_DIR_API_LOGS'), 1, translate('GENERAL_CHECKENV_REQUIREWREITABLE')),
        '/api/application/languages/' => array(translate('GENERAL_CHECKENV_DIR_API_LANG'), 1, translate('GENERAL_CHECKENV_REQUIREWREITABLE')),
        '/application/configs/config.php' => array(translate('GENERAL_CHECKENV_DIR_APP_CONFIG'), 1, translate('GENERAL_CHECKENV_REQUIREWREITABLE')),
        '/application/logs/' => array(translate('GENERAL_CHECKENV_DIR_APP_LOGS'), 1, translate('GENERAL_CHECKENV_REQUIREWREITABLE')),
        '/application/datas/' => array(translate('GENERAL_CHECKENV_DIR_APP_DATAS'), 1, translate('GENERAL_CHECKENV_REQUIREWREITABLE')),
        site_url('/application/datas/') => array(translate('GENERAL_CHECKENV_DIR_ADMIN_DATAS'), 1, translate('GENERAL_CHECKENV_REQUIREWREITABLE')),
        site_url('/application/logs/') => array(translate('GENERAL_CHECKENV_DIR_ADMIN_LOGS'), 1, translate('GENERAL_CHECKENV_REQUIREWREITABLE')),
    );
    $phpversiON = phpversion();
    $versiON_msg = versiON_compare(PHP_VERSION, '5.3.0', '<') ? translate('GENERAL_CHECKENV_INFO_RECOMMEND_VERSION') : "<span class='blue'>√<span>";
    $run_env = strtoupper(php_sapi_name());
    $os = PHP_OS;
    $is_rewrite = false;
    if (($is_apache = strpos($run_env, 'APACHE')) !== false) {
        $apache_list = apache_get_modules();
        $is_rewrite = array_search('mod_rewrite', $apache_list) ? true : false;
        unset($apache_list);
    }
    foreach ($dir as $key => &$val) {
        $temp = is_writeable(dirname(ROOTPATH) . $key);
        $val['value'] = $temp ? translate('GENERAL_CHECKENV_WREITABLE') : translate('GENERAL_CHECKENV_UNWREITEBLE');
        if ($temp == $val[1]) {
            $val['message'] = '<span class="blue">√</span>';
        } else {
            $val['message'] = '<span class="red">' . $val[2] . '</span>';
        }
    }
    foreach ($info as $key => &$val) {
        $var = get_cfg_var($key) ? get_cfg_var($key) : ini_get($key);
        $val['value'] = ($var == 0) ? 'OFF' : (($var == 1) ? 'ON' : $var);
        if (is_numeric($val[1]) || $val['value'] == $val[1]) {
            $val['message'] = '<span class="blue">√</span>';
        } else {
            $val['message'] = '<span class="red">' . $val[2] . '</span>';
        }
    }
    foreach ($fun as $key => &$val) {
        $val['value'] = function_exists($key) ? 'ON' : 'OFF';
        if (is_numeric($val[1]) || $val['value'] == $val[1]) {
            $val['message'] = '<span class="blue">√</span>';
        } else {
            $val['message'] = '<span class="red">' . $val[2] . '</span>';
        }
    }

    $moban = "<table width='100%' border='0' cellspacing='1' cellpadding='0' class='tablegrid'>
        <tr class='title'><td>" . translate('GENERAL_CHECKENV_INFO_PARAMS') . "</td><td colspan='2'></td></tr>
        <tr><th>" . translate('GENERAL_CHECKENV_INFO_DOMAINIP') . "：</th><td colspan='2'>{$_SERVER['SERVER_NAME']} [{$_SERVER['REMOTE_ADDR']}]</td></tr>
        <tr><th>" . translate('GENERAL_CHECKENV_INFO_PORT') . "：</th><td colspan='2'>{$_SERVER['SERVER_PORT']}</td></tr>
        <tr><th>" . translate('GENERAL_CHECKENV_INFO_SOFTWARE') . "：</th><td colspan='2'>{$_SERVER['SERVER_SOFTWARE']}</td></tr>
        <tr><th>" . translate('GENERAL_CHECKENV_INFO_OS') . "：</th><td colspan='2'>{$os}</td></tr>
        <tr><th>" . translate('GENERAL_CHECKENV_INFO_ROOT') . "：</th><td colspan='2'>{$_SERVER['DOCUMENT_ROOT']}</td></tr>
        <tr><th>" . translate('GENERAL_CHECKENV_INFO_FILENAME') . "：</th><td colspan='2'>{$_SERVER['SCRIPT_FILENAME']}</td></tr>
        <tr class='title'>
            <td class='title'>" . translate('GENERAL_CHECKENV_INFO_VARNAME') . "</td><td class='title'>" . translate('STATUS') . "</td><td class='title'>" . translate('GENERAL_CHECKENV_INFO_COMMEND') . "</td>
        </tr>
        <tr><th>" . translate('GENERAL_CHECKENV_INFO_PHP_VERSION') . "</th><td>{$phpversiON}</td><td>{$versiON_msg}</td></tr>
        <tr><th>" . translate('GENERAL_CHECKENV_INFO_PHP_MODE') . "</th><td>{$run_env}</td><td><span class='blue'>√<span></td></tr>";
    $moban .="<tr><th>REWRITE</th><td>";
    if ($is_apache === false) {
        $moban .= translate('UNKNOWN') . "</td><td></td></tr>";
    } else {
        $moban .= ($is_rewrite) ? '<span color="green">' . translate('OPEN') . '</span>' : '<span class="red">' . translate('CLOSE') . '</span>';
        $moban .="</td><td>" . $is_rewrite ? "</td><td><span class='blue'>√<span>" : "<span class='red'>" . translate('REQUIRE') . "<span>" . "</td></tr>";
    }

    $moban .="<tr class='title'><td>" . translate('GENERAL_CHECKENV_DIR') . "</td><td colspan='2'></td></tr>";
    foreach ($dir as $m => $n) {
        $moban.="<tr><th>{$n[0]} [{$m}]</th><td>{$n['value']}</td><td>{$n['message']}</td></tr>";
    }

    $moban .="<tr class='title'><td>" . translate('GENERAL_CHECKENV_INFO') . "</td><td colspan='2'></td></tr>";
    foreach ($info as $m => $n) {
        $moban.="<tr><th>{$n[0]} [{$m}]</th><td>{$n['value']}</td><td>{$n['message']}</td></tr>";
    }

    $moban .="<tr class='title'><td>" . translate('GENERAL_CHECKENV_FUNC') . "</td><td colspan='2'></td></tr>";

    foreach ($fun as $m => $n) {
        $moban.="<tr><th>{$n[0]} [{$m}]</th><td>{$n['value']}</td><td>{$n['message']}</td></tr>";
    }
    $moban .= "</table>";
    return $moban;
}